package com.aijk.web.admin.utils;

import com.aijk.commons.lang.utils.StringUtil;
import com.aijk.commons.utils.Utils;

import javax.servlet.http.HttpServletRequest;

public class RequestUtil {

	/**
	 * 获取Http协议
	 * @param request HttpServletRequest
	 * @return URL
	 */
	public static String getProtocol(HttpServletRequest request) {
		String protocol = request.getHeader("x-forwarded-proto");
		if (Utils.isEmpty(protocol)) {
			protocol = request.getScheme();
		}
		return protocol;
	}

	/**
	 * 获取服务器URL
	 * @param request HttpServletRequest
	 * @return URL
	 */
	public static String getServerUrl(HttpServletRequest request) {
		String serverurl = getProtocol(request);
		serverurl += "://" + request.getServerName();
		int port = request.getServerPort();
		return (port == 80) ? serverurl : (serverurl + ":" + port);
	}
	
	/**
	 * 获取WebApp工程URL
	 * @param request HttpServletRequest
	 * @return URL
	 */
	public static String getWebAppUrl(HttpServletRequest request) {
		return getServerUrl(request) + request.getContextPath();
	}

	/**
	 * 获取重定向URI
	 * @param request HttpServletRequest
	 * @return URI
	 */
	public static String getRedirectUri(HttpServletRequest request) {
		String redirectUri = request.getServletPath();
		String queryString = request.getQueryString();
		if (StringUtil.isNotBlank(queryString)) {
			redirectUri = (redirectUri + "?" + queryString);
		}
		return redirectUri;
	}

	public static boolean isAjaxRequest(HttpServletRequest request) {
		return "XMLHttpRequest".equals(request.getHeader("x-requested-with"));
	}
	
}
